package www.dianbaozu.com.view.popuview

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.LinearLayout.SHOW_DIVIDER_MIDDLE
import android.widget.TextView
import androidx.annotation.ColorRes
import com.lxj.xpopup.core.BottomPopupView
import www.wen.com.common.R
import www.wen.com.common.lib.extension.getColorAgency
import www.wen.com.common.lib.extension.setOnClickListenerAgency
import www.wen.com.common.lib.helper.BottomOptionFunction
import www.wen.com.common.lib.helper.CancelFunction
import www.wen.com.common.lib.util.DisplayUtil


/**
 * @author WEN
 * @Description:底部选择弹框
 * @date 2021/3/3 14:53
 */
abstract class BaseBottomOptionPopupView(
    context: Context,
    open val content: CharSequence,
    open val innerLayoutId: Int,
    open val dismissOnSelectOption:Boolean = true,
    @ColorRes open val colorId:Int = R.color.color111111,
    open var cancelFunction: CancelFunction? = null,
    open var bottomOptionFunction: BottomOptionFunction? = null
) : BottomPopupView(context), View.OnClickListener {

    private lateinit var cancelView: View

    private lateinit var container: LinearLayout

    override fun getImplLayoutId(): Int = R.layout.popupview_base_bottom_option

    override fun onCreate() {
        super.onCreate()
        cancelView = findViewById(R.id.cancel)
        container = findViewById(R.id.container)

        container.showDividers = SHOW_DIVIDER_MIDDLE
        container.post {
            container.dividerDrawable = getDividerDrawable(container)
        }
        if (cancelView is TextView) {
            (cancelView as TextView).text = content
        }

        LayoutInflater.from(context).inflate(innerLayoutId, container, true)

        for (i in 0 until container.childCount) {
            container.getChildAt(i).setOnClickListener {
                if(dismissOnSelectOption) dismiss()
                bottomOptionFunction?.invoke(container.indexOfChild(it))
            }
        }

        setOnClickListenerAgency(this, cancelView)
    }

    /**
     * 返回分割线的Drawable
     */
    open fun getDividerDrawable(view:View): Drawable = ColorDrawable(getColorAgency(colorId)).apply {
        draw(Canvas(
            Bitmap.createBitmap(view.width, DisplayUtil.dip2px(1f).toInt(), Bitmap.Config.RGB_565)
        ))
    }

    override fun onClick(v: View) {

        when (v.id) {
            R.id.cancel -> {
                cancelFunction?.run {
                    invoke(this@BaseBottomOptionPopupView)
                }
                dismiss()
            }
        }
    }

}


